//
//  PlayMusicViewController.m
//  Khmer media
//
//  Created by Rainseylong on 2/12/13.
//  Copyright (c) 2013 imer. All rights reserved.
//

#import "PlayMusicViewController.h"
#import "SONG.h"
#import "ViewFactory.h"
#import "DataManager.h"
#import "AudioStreamer.h"
#import <QuartzCore/CoreAnimation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "MarqueeLabel.h"


#define Padding 20

@interface PlayMusicViewController ()

@end

@implementation PlayMusicViewController

@synthesize playMusicTable;
@synthesize allSongsByAlbume;
@synthesize albumId;
@synthesize playMusicURL;

@synthesize playerNext;
@synthesize playerPre;
@synthesize playerPlay;
@synthesize playerRepeat;
@synthesize playerShuffle;
@synthesize durationEnd;
@synthesize durationStart;
@synthesize progressSlider;
@synthesize progressUpdateTimer;
@synthesize streamURL;
@synthesize isSliderMove;
@synthesize curentSongIndex;
@synthesize shuffle;
@synthesize repeatAll;
@synthesize repeatOne;
@synthesize khmerFont;
@synthesize currentPlaySongIndex;

#pragma mark -
#pragma mark - view mode

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self animateLable];
    self.khmerFont=[UIFont fontWithName:@"KhmerOSFasthand" size:13];
    
    [self loadDataFromServer];
}

-(void)animateLable
{
    // Rate label example
    MarqueeLabel *rateLabelOne=[[MarqueeLabel alloc] initWithFrame:CGRectMake(10, 5, self.view.frame.size.width-20, 20) duration:50.0f andFadeLength:10.0f];
    
    rateLabelOne.numberOfLines = 1;
    rateLabelOne.opaque = NO;
    rateLabelOne.enabled = YES;
    rateLabelOne.fadeLength = 10.f;
    rateLabelOne.shadowOffset = CGSizeMake(0.0, -1.0);
    rateLabelOne.textAlignment = NSTextAlignmentRight;
    rateLabelOne.textColor = [UIColor colorWithRed:0.234 green:0.234 blue:0.234 alpha:1.000];
    rateLabelOne.backgroundColor = [UIColor clearColor];
    rateLabelOne.font = [UIFont fontWithName:@"Helvetica-Bold" size:17.000];
    
    rateLabelOne.text = @"This song in production a in albume of ";
    
    // For Autoresizing test
    rateLabelOne.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:rateLabelOne];
}

-(void)loadDataFromServer
{
    [SONG convertSongsToOBJectWithBlock:^(NSArray *songsArray, NSError *error)
    {
        self.allSongsByAlbume=songsArray;
        [self.playMusicTable reloadData];
        
        self.currentPlaySongIndex=[NSMutableDictionary dictionaryWithCapacity:self.allSongsByAlbume.count];
        [self letPlayStreamByCurrentIndexSong:self.curentSongIndex];
        [self displayPlayImageByNextSongIndex:0 WithPrevSongIndex:0];
        
    } WithSongType:NO ablumeID:self.albumId];
}

#pragma mark -
#pragma mark - tableView block

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allSongsByAlbume.count;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[ViewFactory cellOfKind:@"PlayMusicCell" forTable:tableView];
    
    UILabel *songTitle=(UILabel *)[cell viewWithTag:30];
    UILabel *indexSong=(UILabel *) [cell viewWithTag:31];
    UIImageView *isPlay=(UIImageView *)[cell viewWithTag:32];
    
    SONG *objSongs=[self.allSongsByAlbume objectAtIndex:indexPath.row];

    songTitle.font=self.khmerFont;
    songTitle.text=objSongs.songTitle;
    
    indexSong.text=[NSString stringWithFormat:@"%d",indexPath.row +1];
    
    CGSize sizeToFit = [objSongs.songTitle sizeWithFont:self.khmerFont constrainedToSize:CGSizeMake(220.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];
    
    [songTitle setFrame:CGRectMake(65,2 ,220,sizeToFit.height + Padding )];
    
    if ([[self.currentPlaySongIndex objectForKey:[NSString stringWithFormat:@"pay@_%d",indexPath.row]] isEqualToString:@"YES"])
    {
        isPlay.hidden=NO;
    }
    else
    {
        isPlay.hidden=YES;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SONG *objSongs=[self.allSongsByAlbume objectAtIndex:indexPath.row];
    UIFont *khmerfont=[UIFont fontWithName:@"KhmerOSFasthand" size:13];
    CGSize sizeToFit = [objSongs.songTitle sizeWithFont:khmerfont constrainedToSize:CGSizeMake(220.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];
    
    return fmaxf(30.0f, sizeToFit.height + 30.0f);
}

#pragma mark -
#pragma mark - audion controller delgate 

-(IBAction)touchPlay:(id)sender
{
    if ([[DataManager sharedDataManager].streamer isPlaying])
    {
        [[DataManager sharedDataManager].streamer pause];
        [self.playerPlay setImage:[UIImage imageNamed:@"AudioPlayerPlay.png"] forState:UIControlStateNormal];
    }
    else
    {
        [[DataManager sharedDataManager].streamer start];
        [self.playerPlay setImage:[UIImage imageNamed:@"AudioPlayerPause.png"] forState:UIControlStateNormal];
    }
}
-(IBAction)touchNext:(id)sender
{
    [self delegateNextButton];
}

-(void)displayPlayImageByNextSongIndex:(int)nextIndex
                     WithPrevSongIndex:(int)prevIndex
{
    if (nextIndex==0 && prevIndex==0)
    {
        [self.currentPlaySongIndex setValue:@"YES" forKey:[NSString stringWithFormat:@"pay@_%d",nextIndex]];
    }
    else
    {
        [self.currentPlaySongIndex setValue:@"YES" forKey:[NSString stringWithFormat:@"pay@_%d",nextIndex]];
        [self.currentPlaySongIndex setValue:@"NO" forKey:[NSString stringWithFormat:@"pay@_%d",prevIndex]];
    }
}

-(void)delegateNextButton
{
    int newIndex;
	
	if (self.shuffle)
	{
		newIndex = rand() % [self.allSongsByAlbume count];
	}
	else if (self.repeatOne)
	{
		newIndex = self.curentSongIndex;
	}
	else if (self.repeatAll)
	{
		if (self.curentSongIndex + 1 == [self.allSongsByAlbume count])
			newIndex = 0;
		else
			newIndex = self.curentSongIndex + 1;
	}
	else
	{
		newIndex = self.curentSongIndex + 1;
	}
	self.curentSongIndex = newIndex;
    
    [self letPlayStreamByCurrentIndexSong:self.curentSongIndex];
    [self displayPlayImageByNextSongIndex:self.curentSongIndex WithPrevSongIndex:self.curentSongIndex -1];
}

-(void)letPlayStreamByCurrentIndexSong:(int)songIndex
{
    //update cell
    [self updatePlayImageOnCellWithIndex:self.curentSongIndex];
    
    SONG *testSongObj=[self.allSongsByAlbume objectAtIndex:songIndex];
    
    NSString *productionName=[DataManager sharedDataManager].productionName;
    NSString *albumeName=[DataManager sharedDataManager].albumeName;
    self.streamURL=[NSString stringWithFormat:@"%@%@%@%@",PlayMusicUrl,productionName,albumeName,testSongObj.songUrl];
    
    [self destroyStreamer];
    [self createStreamer];
    [[DataManager sharedDataManager].streamer start];
}

-(IBAction)touchPre:(id)sender
{
   	int newIndex = self.curentSongIndex - 1;
    
    if (newIndex >=0)
    {
        self.curentSongIndex = newIndex;
        
        [self letPlayStreamByCurrentIndexSong:self.curentSongIndex];
        [self displayPlayImageByNextSongIndex:self.curentSongIndex WithPrevSongIndex:self.curentSongIndex +1];
    }
}
-(IBAction)touchRepeat:(id)sender
{
    if (self.repeatOne)
	{
        [self.playerRepeat setImage:[UIImage imageNamed:@"AudioPlayerRepeatOff.png"]
                           forState:UIControlStateNormal];

		self.repeatOne = NO;
		self.repeatAll = NO;
	}
	else if (self.repeatAll)
	{
        [self.playerRepeat setImage:[UIImage imageNamed:@"AudioPlayerRepeatOneOn.png"]
                           forState:UIControlStateNormal];

		self.repeatOne = YES;
		self.repeatAll = NO;
	}
	else
	{
        [self.playerRepeat setImage:[UIImage imageNamed:@"AudioPlayerRepeatOn.png"]
                           forState:UIControlStateNormal];
        
		self.repeatOne = NO;
		self.repeatAll = YES;
	}
}

-(IBAction)touchShuffle:(id)sender
{
    if (self.shuffle)
	{
		self.shuffle = NO;
        [self.playerShuffle setImage:[UIImage imageNamed:@"AudioPlayerShuffleOff.png"]
                            forState:UIControlStateNormal];
	}
	else
	{
		self.shuffle = YES;
        [self.playerShuffle setImage:[UIImage imageNamed:@"AudioPlayerShuffleOn.png"]
                            forState:UIControlStateNormal];
	}
}

- (BOOL)canGoToNextTrack
{
	if (self.curentSongIndex + 1 == [self.allSongsByAlbume count])
		return NO;
	else
		return YES;
}

#pragma mark -
#pragma mark - Stream block controller

- (void)destroyStreamer
{
	if ([DataManager sharedDataManager].streamer)
	{
		[[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:ASStatusChangedNotification
                                                      object:[DataManager sharedDataManager].streamer];
        [progressUpdateTimer invalidate];
		progressUpdateTimer = nil;
		
		[[DataManager sharedDataManager].streamer stop];
		[DataManager sharedDataManager].streamer = nil;
	}
}

- (void)createStreamer
{
	if ([DataManager sharedDataManager].streamer)
	{
		return;
	}
	[self destroyStreamer];
	
	NSString *escapedValue =(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                 nil,
                                                                                 (CFStringRef)self.streamURL,
                                                                                 NULL,
                                                                                 NULL,
                                                                                 kCFStringEncodingUTF8));
	NSURL *url = [NSURL URLWithString:escapedValue];
    @try {
        [[DataManager sharedDataManager] startStreamerWithURL:url];
    }
    @catch (NSException *exception) {
        NSLog(@"create stream faile !");
    }
    @finally {
        progressUpdateTimer =[NSTimer scheduledTimerWithTimeInterval:0.1
                                                              target:self
                                                            selector:@selector(updateProgress:)
                                                            userInfo:nil
                                                             repeats:YES];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateChanged:)
                                                     name:ASStatusChangedNotification
                                                   object:[DataManager sharedDataManager].streamer];
    }
}

-(void)startStream
{
    if ([[DataManager sharedDataManager].streamer isPlaying])
    {
        [self.playerPlay setImage:[UIImage imageNamed:@"AudioPlayerPause.png"] forState:UIControlStateNormal];
    }
    else if ([[DataManager sharedDataManager].streamer isPaused])
    {
        [self.playerPlay setImage:[UIImage imageNamed:@"AudioPlayerPlay.png"] forState:UIControlStateNormal];
        [self createStreamer];
        [[DataManager sharedDataManager].streamer start];
    }
}

- (IBAction)sliderMoved:(UISlider *)aSlider
{
	if ([DataManager sharedDataManager].streamer.duration)
	{
		[[DataManager sharedDataManager].streamer seekToTime:aSlider.value];
        [self updateCurrentTimeForPlayer:[DataManager sharedDataManager].streamer];
	}
}

- (void)playbackStateChanged:(NSNotification *)aNotification
{
    if ([[DataManager sharedDataManager].streamer isWaiting])
	{
	}
	else if ([[DataManager sharedDataManager].streamer isPlaying])
	{
		[self.playerPlay setImage:[UIImage imageNamed:@"AudioPlayerPause.png"] forState:UIControlStateNormal];
        self.progressSlider.maximumValue=[DataManager sharedDataManager].streamer.duration;
	}
	else if ([[DataManager sharedDataManager].streamer isIdle])//End of Stream
	{
        if ([self canGoToNextTrack])
        {
           [self delegateNextButton]; 
        }
        else
        {
            [self destroyStreamer];
            [[DataManager sharedDataManager].streamer stop];
        }
	}
}

- (void)updateProgress:(NSTimer *)updatedTimer
{
	if ([DataManager sharedDataManager].streamer.bitRate != 0.0)
	{
        [self updateCurrentTimeForPlayer:[DataManager sharedDataManager].streamer];
	}
	else
	{
		self.durationStart.text= @"0:00";
	}
}

-(void)updateCurrentTimeForPlayer:(AudioStreamer *)au
{
    double currentTime = au.progress;
    double duration = au.duration;
    
    NSString *current = [NSString stringWithFormat:@"%d:%02d", (int)currentTime / 60, (int)currentTime % 60, nil];
    NSString *dur = [NSString stringWithFormat:@"-%d:%02d", (int)((int)(duration - currentTime)) / 60, (int)((int)(duration - currentTime)) % 60, nil];
    
    self.durationStart.text=current;
    self.durationEnd.text=dur;
    
    if (au.isPlaying)
    {
        self.progressSlider.value=(float)currentTime;
    }
}

-(void)updatePlayImageOnCellWithIndex:(int)index
{
    NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:index inSection:0];
    NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil];
    
    [self.playMusicTable beginUpdates];
    
    [self.playMusicTable reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];
    [self.playMusicTable scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    
    [self.playMusicTable endUpdates];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
